package me.jiatao.paging3.paging3

import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import androidx.paging.*
import kotlinx.coroutines.flow.Flow
import me.jiatao.paging3.MyApplication
import me.jiatao.paging3.network.pojo.ArticleItem
import me.jiatao.paging3.paging3.mediator.ProjectRemoteMediator
import me.jiatao.paging3.room.ArticleEntity

class ProjectViewModel : ViewModel() {
    private val pageSize = 10

    /**
     * PagerConfig 可以提供分页的参数，比如每一页的加载数、初始加载数和最大数等。
     */
    private val config = PagingConfig(
        pageSize = pageSize,
        initialLoadSize = pageSize,
        enablePlaceholders = false,
        prefetchDistance = 4
    )

    /**
     * config 分页的参数
     * pagingSourceFactory 单一数据源的工厂，在闭包中提供一个PageSource即可
     * remoteMediator 同时支持网络请求和数据库请求的数据源
     * initialKey 初始化使用的key
     */
    @ExperimentalPagingApi
    private val projectPage = Pager(
        config = config,
        //pagingSourceFactory = { ProjectPagingSource() },
        remoteMediator = ProjectRemoteMediator(),
        pagingSourceFactory = { MyApplication.getDB().articleDao().loadAllByIds() }
    )

    @ExperimentalPagingApi
    fun getProjectPageFlow(): LiveData<PagingData<ArticleEntity>> {
        /**
         * cachedIn()函数，这是用于将服务器返回的数据在viewModelScope这个作用域内进行缓存，
         * 假如手机横竖屏发生了旋转导致Activity重新创建，Paging3就可以直接读取缓存中的数据，而不用重新发起网络请求了。
         */
        return projectPage.flow.cachedIn(viewModelScope).asLiveData()
    }
}